package userModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/jwts"
	"KumquatDrivesServices/model"
	"errors"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type UserLoginRequest struct {
	UserRequest
}

func (UserModuleApi) UserLogin(c *gin.Context) {
	var req UserLoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	var UserModule model.UserModel
	if err := global.DB.Where("user_email=?", req.UserEmail).First(&UserModule).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.FailWithCode(res.ACCOUNT_OR_PWD_ERR, c)
			return
		}
		logrus.Errorf("get user error: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	bol, checkPwdErr := CheckPassword(UserModule.Password, req.Password)
	if checkPwdErr != nil {
		logrus.Errorf("check password error: %v", checkPwdErr)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	if !bol {
		res.FailWithCode(res.ACCOUNT_OR_PWD_ERR, c)
		return
	}

	accessToken, refreshToken, err := jwts.GenerateToken(UserModule.ID)
	if err != nil {
		logrus.Errorf("generate token error: %v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	c.Header("accessToken", accessToken)
	c.Header("refreshToken", refreshToken)
	if CacheErr := UserModule.CacheUserInfo(); CacheErr != nil {
		logrus.Errorf("cache user info error: %v", CacheErr)
	}
	res.OkWithData(UserModule, c)
}
